// pages/container/shopping-cart/shopping-cart.js
const tool = require("../../../utils/util.js");
const server = require("../../../utils/server.js");
const app = getApp();
const getSetData = tool.getSetData;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageShow: false,
    isIPhoneX: app.globalData.isIPhoneX,
    cartData: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const _this = this;
    const member_id = wx.getStorageSync('userInfo').member_id;
    var param = {
      member_id: member_id
    };
    wx.showLoading({
      title: '加载中',
    });
    server.postJSON("/index/cart/cart_list", param, function(res) {
      wx.hideLoading();
      _this.setData({
        pageShow: true
      });
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      let cartData = [];
      if (res.data.data && res.data.data.length > 0) {
        for (var i = 0; i < res.data.data.length; i++) {
          if (res.data.data[i].is_collocation == 2) {
            res.data.data[i].cart_label = "搭配购";
          }
          if (!res.data.data[i].identification) {
            res.data.data[i].is_collocation = 1;
          }
          res.data.data[i].checked = false;
        }
      }
      _this.setData({
        cartData: res.data.data ? res.data.data : []
      })
      // 计算总价
      _this.checkedGoodsTotalPrice();
      // 是否全选
      _this.isAllChecked();
    });
  },
  /**
   * 选中/取消单个商品
   */
  checkItem(e) {
    const _this = this;
    const cart_id = tool.getDataset(e).cartId;
    const identification = tool.getDataset(e).identification;
    console.log(e)
    const cartData = _this.data.cartData
    for (var i = 0; i < _this.data.cartData.length; i++) {
      if (identification && identification == cartData[i].identification) {
        cartData[i].checked = !cartData[i].checked
      } else if (cartData[i].cart_id == cart_id) {
        cartData[i].checked = !cartData[i].checked
      }
    }
    _this.setData({
      cartData: cartData
    })
    // 计算总价
    _this.checkedGoodsTotalPrice();
    // 是否全选
    _this.isAllChecked();
  },
  allCheckedHandle() {
    const _this = this;
    let isAllChecked = _this.data.isAllChecked;
    let cartData = _this.data.cartData;
    _this.setData({
      isAllChecked: !isAllChecked
    });
    for (var i = 0; i < cartData.length; i++) {
      cartData[i].checked = !isAllChecked
    }
    _this.setData({
      cartData: cartData
    });
    _this.checkedGoodsTotalPrice();
  },
  /**
   * 判断是否全部选中
   */
  isAllChecked() {
    const _this = this;
    let cartData = _this.data.cartData;
    const noCheckedItems = cartData.filter(function(item) {
      if (!item.checked) {
        return item
      }
    });
    _this.setData({
      isAllChecked: noCheckedItems.length == 0 ? true : false
    })
  },
  /**
   * 减少购物车单个商品数量
   */
  minusCartItem(e) {
    const _this = this;
    const cart_id = tool.getDataset(e).cartId;
    const param = {
      cart_id: cart_id,
      member_id: app.globalData.userInfo.member_id
    }
    let cartData = _this.data.cartData;
    for (var i = 0; i < cartData.length; i++) {
      if (cartData[i].cart_id == cart_id) {
        if (cartData[i].goods_num > 1) {
          cartData[i].goods_num--;
          param.goods_id = cartData[i].goods_id;
          param.goods_num = cartData[i].goods_num;
          server.postJSON("/index/cart/cart_edit_quantity", param, function(res) {
            if (res.data.error !== 0) {
              tool.warning(res.data.message);
              return;
            }
            _this.setData({
              cartData: cartData
            });
          })
        } else {
          tool.warning("我也是有底线的。")
        }
      }
    }
  },
  /**
   * 增加购物车单个商品数量
   */
  addCartItem(e) {
    const _this = this;
    const cart_id = tool.getDataset(e).cartId;
    const param = {
      cart_id: cart_id,
      member_id: app.globalData.userInfo.member_id
    }
    let cartData = _this.data.cartData;
    for (var i = 0; i < cartData.length; i++) {
      if (cartData[i].cart_id == cart_id) {
        cartData[i].goods_num++;
        param.goods_id = cartData[i].goods_id;
        param.goods_num = cartData[i].goods_num;
        server.postJSON("/index/cart/cart_edit_quantity", param, function(res) {
          if (res.data.error !== 0) {
            tool.warning(res.data.message);
            return;
          }
          _this.setData({
            cartData: cartData
          });
        })
      }
    }
  },
  /**
   * 计算选中商品的总价
   */
  checkedGoodsTotalPrice() {
    const _this = this;
    let cartData = _this.data.cartData;
    let totalPrice = 0;
    for (var i = 0; i < cartData.length; i++) {
      if (cartData[i].checked) {
        totalPrice += cartData[i].goods_price * cartData[i].goods_num
      }
    }
    _this.setData({
      totalPrice: totalPrice
    })
  },
  /**
   * 删除当个购物车商品
   */
  delCartItem(e) {
    const _this = this;
    const cart_id = tool.getDataset(e).cartId;
    const param = {
      cart_id: cart_id,
      member_id: app.globalData.userInfo.member_id
    }
    server.postJSON("/index/cart/cart_del", param, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      const cartIdStr = res.data.data.join(',');
      let cartData = _this.data.cartData.filter(function(item) {
        if (cartIdStr.indexOf(item.cart_id) < 0) {
          return item;
        }
      });
      _this.setData({
        cartData: cartData
      })
      _this.isAllChecked();
      _this.checkedGoodsTotalPrice();
    });
  },
  /**
   * 跳转到确认订单页面，
   * 选中的商品数据保存到全局变量globalData.confirmOrderData中，{
   * from: cart,
   * data: []
   * }
   * 并标明来自购物车 
   */
  toConfirmOrderPage() {
    const _this = this;
    let cartData = _this.data.cartData;
    cartData = cartData.filter(item => {
      if (item.checked) {
        return item;
      }
    });
    if (cartData.length == 0) {
      tool.warning("客官您忘记选商品了。");
      return;
    }
    const cartIdArr = cartData.reduce(function(prev, next) {
      prev.push(next.cart_id);
      return prev;
    }, []);
    if (!tool.lockClick()) {
      return;
    }
    const cartIdString = cartIdArr.join(",");
    let confirmOrderData = {
      "from": "cart",
      "data": cartIdString,
      "totalPrice": _this.data.totalPrice
    }
    confirmOrderData = JSON.stringify(confirmOrderData);
    wx.navigateTo({
      url: '/pages/container/confirm-order-details/confirm-order-details?confirmOrderData=' + confirmOrderData,
      success: function() {
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})